﻿define(["vue", "axios"], function (Vue, axios) {

    //默认地址
    //axios.defaults.baseURL = "http://192.168.0.103/isperp-itss/api/wechat/v2/";
    axios.defaults.baseURL = "/itsm/api/wechat/v2/";
    
    //var ddurl ="http://172.20.10.5:8080/";
    var ddurl ="http://hc.isperp.com/itsm/";
    //var ddurl ="http://localhost:8080/";
    
    axios.interceptors.request.use(
        function (config) {
            config.url = encodeURI(config.url);
            return config;
        }, function (error) {
            return Promise.reject(error);
        });

    axios.defaults.params = {
        username: localStorage.getItem("username")
    }

    Vue.prototype.isloading = false;

    var check = function (d, log) {
        if (d && typeof (d.success) != "undefined" && !d.success) {
            console.log(log);
        }
    }
    //拦截器
    axios.defaults.transformResponse.push(function (data) {
        if (data && typeof (data.success) != "undefined" && !data.success) {
            //alert(data.message);
            throw data.message;
        } else {
            return data;
        }
    });

    var setUsername = function (username) {
        localStorage.setItem("username", username);
        axios.defaults.params = {
            username: username
        };
    }

    var getUsername = function () {
        return localStorage.getItem("username");
    }

    var isEmpty = function (value) {
        return typeof (value) == "undefined" || value == null || value == "";
    }

    var setColumn = function (data) {
        data.columns = [];
        for (var column in data.data) {
            data.columns.push(column);
        }
    }

    var getParam = function (name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) {
            return decodeURI(r[2]);
        }
        return null;
    }

    var goback = function (url) {
        window.history.back();
    }

    var calendar = {
        getDay: function (day) {
            switch (day) {
                case "0":
                    return "周日";
                case "1":
                    return "周一";
                case "2":
                    return "周二";
                case "3":
                    return "周三";
                case "4":
                    return "周四";
                case "5":
                    return "周五";
                case "6":
                    return "周六";
            }

        }
    }

    var getFontSize = function (originalSize) {
        var realSize = document.body.clientWidth * originalSize / 750;
        return realSize;
    }

    var convertImgToBase64 = function (url, callback, outputFormat) {
        var canvas = document.createElement('CANVAS');
        var ctx = canvas.getContext('2d');
        var img = new Image;
        img.crossOrigin = 'Anonymous';
        img.onload = function () {
            var width = img.width;
            var height = img.height;
            // 按比例压缩4倍
            var rate = (width < height ? width / height : height / width) / 4;
            canvas.width = width * rate;
            canvas.height = height * rate;
            ctx.drawImage(img, 0, 0, width, height, 0, 0, width * rate, height * rate);
            var dataURL = canvas.toDataURL(outputFormat || 'image/png');
            callback.call(this, dataURL);
            canvas = null;
        };
        img.src = url;
    }

    var compressImg = function (imgData, maxHeight, type, callback) {
        var canvas = document.createElement("canvas");
        var img = new Image();
        img.onload = function () {
            if (img.height > maxHeight) {
                img.width *= maxHeight / img.height;
                img.height = maxHeight;
            }
            canvas.width = img.width;
            canvas.height = img.height;
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, img.width, img.height);
            callback(canvas.toDataURL(type));
            delete canvas;
        };
        img.src = imgData;
    }

    var imgUpload = function (event, images, error) {
        var file = event.target.files[0];
        if (!/image\/\w+/.test(file.type)) {
            error("请确保文件为图像类型");
            return;
        }
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function (e) {
            compressImg(this.result, 600, file.type, function (data) {
                images.push({
                    name: file.name,
                    data: data
                });
            });
        };
    }
    
   

    var code = getParam("code");
    if (!isEmpty(code)) {
        var existCode = localStorage.getItem("code");
        localStorage.setItem("code", code);
        if (existCode != code) {
            /*axios.get("wechat/getCurrentUser?code=" + code)
                .then(function (response) {
                    var username = response.data;
                    setUsername(username);
                });*/
        	 setUsername(code);
        }
    }
    
    var dingding =null;
    if (!isEmpty(dingding)) {
        axios.get(ddurl+"api/dingding/getconfig?url="+window.location.href)
            .then(function (response) {
                var _config = response.data;
                //alert("_config"+_config);
                dd.config({
            		agentId : _config.agentid,
            		corpId : _config.corpId,
            		timeStamp : _config.timeStamp,
            		nonceStr : _config.nonceStr,
            		signature : _config.signature,
            		jsApiList : [ 'runtime.info', 'biz.contact.choose',
            				'device.notification.confirm', 'device.notification.alert',
            				'device.notification.prompt', 'biz.ding.post',
            				'biz.util.openLink' ]
            	});
                
                /*if(ddurl=="http://localhost:8080/"){
                	setUsername("测试1");
                }*/
                dd.ready(function() {
                    dd.biz.navigation.setTitle({
                        title: 'IT服务平台',
                        onSuccess: function(data) {
                        },
                        onFail: function(err) {
                            log.e(JSON.stringify(err));
                        }
                    });
                	dd.runtime.info({
                		onSuccess : function(info) {
                			logger.e('runtime info: ' + JSON.stringify(info));
                		},
                		onFail : function(err) {
                			logger.e('fail: ' + JSON.stringify(err));
                		}
                	});
                	dd.ui.pullToRefresh.enable({
                	    onSuccess: function() {
                	    },
                	    onFail: function() {
                	    }
                	})

                	dd.runtime.permission.requestAuthCode({
                		corpId : _config.corpId,
                		onSuccess : function(info) {
                			//alert('authcode: ' + info.code);
                			$.ajax({
                				url : ddurl+'api/dingding/userinfo?code=' + info.code + '&corpid='
                						+ _config.corpId,
                				type : 'GET',
                				success : function(data, status, xhr) {
                				    alert(data);
                					var info = JSON.parse(data);
                					
                					//alert(info.userid);
                					setUsername(info.jobnumber);

                				},
                				error : function(xhr, errorType, error) {
                					logger.e("yinyien:" + _config.corpId);
                					alert(errorType + ', ' + error);
                				}
                			});

                		},
                		onFail : function(err) {
                			alert('fail: ' + JSON.stringify(err));
                		}
                	});
                });

                dd.error(function(err) {
                	alert('dd error: ' + JSON.stringify(err));
                });
                
                
            });
    }
    
    
    

    return {
        setUsername: setUsername,
        getUsername: getUsername,
        isEmpty: isEmpty,
        setColumn: setColumn,
        getParam: getParam,
        goback: goback,
        calendar: calendar,
        getFontSize: getFontSize,
        imgUpload: imgUpload,
        ddurl:ddurl
    }
});